<template>
  <page-wrap :bgColor="dynamicColor" txtColor="#222" :showTop="false" :dark="true" back hideTab>
    <view class="ai-resume-diagnose-new" :style="'padding-top:' + navHeight + 'px;'">
      <view class="title-box">
        <view class="title"> AI简历诊断 </view>
        <view class="title-desc">
          快捷导入，智能分析，精准分析你的简历问题
        </view>
      </view>
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view class="form-item-wrap" @click.capture="handleSelect(index)">
            <u-form-item :class="[{ pick: item.comp }, { multiple: item.multiple }]" :label="item.label"
              :prop="item.prop" :border-bottom="!item.hideBorderBottom" :required="item.required">
              <u-input v-if="item.comp === 'select'" :class="['form-input']" v-model="form[item.prop]"
                :disabled="!!item.comp" :placeholder="item.inputPlaceholder" :type="item.inputType"
                :height="item.height" :maxlength="item.maxlength || 150" :clearable="false" :id="item.prop" />
              <template v-if="item.comp === 'file'">
                <view v-if="resumeParams.attName" class="file">
                  <image class="file-icon" :src="appendixImg"></image>
                  <view class="file-name">
                    <view class="att_name">{{ resumeParams.attName }}</view>
                    <view class="date" v-if="resumeParams.updateTime">{{ resumeParams.updateTime }} 上传
                    </view>
                  </view>
                </view>
                <u-input v-else :class="['form-input']" v-model="form[item.prop]" :disabled="!!item.comp"
                  :placeholder="item.inputPlaceholder" :type="item.inputType" :height="item.height"
                  :maxlength="item.maxlength || 150" :clearable="false" :id="item.prop" />
              </template>
            </u-form-item>
          </view>
        </block>
      </u-form>
      <view class="footer">
        <view class="btn" @click="handleSubmit">开始诊断</view>
      </view>
    </view>
    <ResumeTypePopup :show.sync="showResumeType" @emitParams="handleGetResumeParams" @close="handleCloseResumeType">
    </ResumeTypePopup>
    <MajorListPopup :show.sync="showMajorList" @close="handleCloseMajorListPopup" @emitParams="handleGetMajorParams">
    </MajorListPopup>
    <WantJobPopup :show.sync="showWantJob" @close="handleCloseWantJobPopup" @emitParams="handleGetWantJobParams">
    </WantJobPopup>
    <LoginDialog @loginSuccessBack="loginSuccessBack"></LoginDialog>
  </page-wrap>
</template>

<script>
import {
  getResumeData,
  syncDealResumeAnalysisAndSave,
  getResumeAnalysisRes,
  capacityDiagnose,
  getCapByPersonId,
  createQR,
  getUserInfo,
  cardRegist,
  addBuryingPoint,
} from "@/api/modules/career";
import { getPersonDetail } from "@/api/index";
import ResumeTypePopup from "./components/ResumeTypePopup";
import MajorListPopup from "./components/MajorListPopup";
import WantJobPopup from "./components/WantJobPopup";
import LoginDialog from "@/components/LoginDialog";
import ShareMixin from "@/mixins/share";
import WxLoginMixin from "@/mixins/wxLogin";
import { env } from "@/api/root";
export default {
  name: "newResume",
  components: {
    ResumeTypePopup,
    MajorListPopup,
    WantJobPopup,
    LoginDialog,
  },
  mixins: [WxLoginMixin, ShareMixin],
  data() {
    return {
      navHeight: getApp().globalData.navHeight,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      appendixImg: this.$imgBaseSelf + "resume/appendix_new.svg",
      dynamicColor: "transparent",
      shareTitle: "快速定位简历问题，给予意向职位能力匹配分析", // 分享自定义标题
      sharePath: "/pagesSub/AIResumeDiagnoseNew/index",
      imageUrl: "",
      form: {
        attName: "",
        major: "",
        position: "",
      },
      formList: [
        {
          label: "导入简历方式",
          prop: "attName",
          propVal: "attName",
          comp: "file",
          show: false,
          inputPlaceholder: "必填",
          required: true,
        },
        {
          label: "选择专业",
          prop: "major",
          propVal: "major",
          comp: "select",
          show: false,
          inputPlaceholder: "必填",
          required: true,
        },
        {
          label: "选择求职意向",
          prop: "position",
          propVal: "position",
          comp: "select",
          show: false,
          inputPlaceholder: "必填",
          required: true,
        },
      ],
      rules: {
        attName: [
          {
            required: true,
            message: "请选择导入简历方式",
          },
        ],
        major: [
          {
            required: true,
            message: "请选择专业",
          },
        ],
        position: [
          {
            required: true,
            message: "请选择求职意向",
          },
        ],
      },
      showResumeType: false,
      showMajorList: false,
      showWantJob: false,
      currentResumeType: {},
      resumeParams: {},
      majorParams: {},
      wantJobParams: {},
      timer: null,
      retryCount: 0,
      MAX_RETRY_TIMES: 5,
      resumeHasAnalysis: false,
      fromSxh: "",
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onShow() {
    uni.$on("wantJobUpdate", () => {
      this.showWantJob = true;
    });
    uni.$on("majorListUpdate", () => {
      this.showMajorList = true;
    });
  },
  onLoad(opt) {
    // imageUrl必须在这里赋值，要不然分享的图片是空的
    this.imageUrl =
      "https://img3.job1001.com/ypMp/elan/images/career/AIResumeDiagnoseNewShare_cover.png";
    if (!this.personId) {
      this.showLoginDialog();
      return;
    }
    this.fromSxh = opt.fromSxh;
    this.getCapByPersonIdFn();

    // uni.$on('wantJobUpdate', () => {
    //   this.showWantJob = true;
    // });
    // uni.$on('majorListUpdate', () => {
    //   this.showMajorList = true;
    // });
  },
  onUnload() {
    uni.$off("wantJobUpdate");
    uni.$off("majorListUpdate");
  },
  created() {},
  methods: {
    async cardRegistFn() {
      const params = {
        personId: this.personId,
      };
      if (env == "test") {
        params.cardType = 54;
      } else if (env == "pro") {
        params.cardType = 28;
      }
      const res = await cardRegist(params);
      return res;
    },
    async loginSuccessBack() {
      this.personId = uni.getStorageSync("person-id").slice(2) || "";
      this.getCapByPersonIdFn();
      await this.getUserInfoFn();
    },
    async getUserInfoFn() {
      uni.showLoading({ title: "" });
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      const res = await getUserInfo({ uid: "" });
      if (res.code == 200) {
        uni.setStorageSync("personName", res.data.personName);
        uni.setStorageSync("cardType", res.data.cardType);
        //如果没有cardType就绑定一个q2c端的
        if (res.data && !res.data.cardType) {
          const registerRes = await this.cardRegistFn();
          uni.hideLoading();
          if (registerRes.code != 200) {
            uni.showToast({
              title: registerRes.status_desc,
              icon: "none",
            });
          } else if (registerRes.code == 200) {
            const infoRes = await getUserInfo({ uid: "" });
            if (infoRes.code == 200) {
              uni.setStorageSync("personName", infoRes.data.personName);
              uni.setStorageSync("cardType", infoRes.data.cardType);
            }
          }
        } else {
          uni.setStorageSync("personName", res.data.personName);
          uni.setStorageSync("cardType", res.data.cardType);
        }
      }
    },
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    async createQRFn() {
      const params = {
        fromPersonId: uni.getStorageSync("SxhPersonId"),
        valueId: 0, // 这里是附件id 不需要复制 直接传0
        rightId: 4, // ai简历诊断4
        shareUrl: "pagesSub/doubleChannelChoosingMeeting/qrCodeParse",
        cardType: uni.getStorageSync("cardType"),
      };
      const res = await createQR(params);
      if (res.code == 200) {
        uni.navigateTo({
          url:
            "/pagesSub/doubleChannelChoosingMeeting/qrCodeResult?from=AIResumeDiagnoseNew" +
            "&buttonText=立即查看结果(不保留)" +
            "&qrCodeText=扫码查看保留AI简历诊断结果" +
            "&qrcodeUrl=" +
            res.data.qRImageBase64,
        });
      }
    },
    async getCapByPersonIdFn() {
      const res = await getCapByPersonId({ personId: this.personId });
      if (res.code == 200) {
        const temp = res.data.info ? JSON.parse(res.data.info) : null;
        if (temp) {
          this.majorParams = { major: temp.major };
          this.wantJobParams = {
            position: temp.position,
            intendedId: temp.intendedId,
          };
          this.resumeParams = {
            attName: temp.attName,
            attUrl: temp.attUrl || "",
            type: temp.type,
            updateTime: temp.updateTime || "",
          };
          this.form.attName = this.resumeParams.attName;
          this.form.major = this.majorParams.major;
          this.form.position = this.wantJobParams.position;
        }
      }
    },
    // 解析上传的简历附件
    async syncDealResumeAnalysisAndSaveFn() {
      uni.showLoading({ title: "解析中...", mask: true });
      const params = {
        fileUrl: this.resumeParams.attUrl,
        personId: this.personId,
      };
      const res = await syncDealResumeAnalysisAndSave(params);
      if (res.code == 200) {
        setTimeout(() => {
          this.startRequest();
        }, 1000);
      } else {
        uni.hideLoading();
        uni.showToast({
          title: res.status_desc,
          icon: "none",
          duration: 1500,
        });
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.getResumeAnalysisResFn();
        } else {
          clearInterval(this.timer);
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      uni.hideLoading();
      this.timer = null;
    },
    // 获取附件简历解析结果状态
    async getResumeAnalysisResFn() {
      try {
        const res = await getResumeAnalysisRes({
          personId: this.personId,
          fileUrl: this.resumeParams.attUrl,
          retryNum: this.retryCount + 1,
        });
        if (res.code === 200) {
          const status = res.data;
          if (status == 0) {
            uni.showToast({
              title: "没有要解析的简历",
              icon: "none",
              duration: 1500,
            });
            this.endRequest();
          } else if (status == 1) {
            uni.showLoading({ title: "解析中..." });
          } else if (status == 2) {
            uni.showToast({
              title: "简历解析失败，请重试",
              icon: "none",
              duration: 1500,
            });
            this.endRequest();
          } else if (status == 3) {
            this.resumeHasAnalysis = true;
            this.endRequest();
            this.getResumeDataFn();
            this.getPersonDetail();
            uni.showToast({
              title: "简历解析成功",
              icon: "none",
              duration: 1500,
            });
          } else {
            uni.showToast({
              title: "未知错误",
              icon: "none",
              duration: 1500,
            });
            this.endRequest();
          }
        } else {
          this.endRequest();
          uni.showToast({
            title: res.status_desc,
            icon: "none",
            duration: 1500,
          });
        }
      } catch (err) {
        this.endRequest();
        uni.showToast({
          title: err.message,
          icon: "none",
          duration: 1500,
        });
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且仍然未解析完成
      if (!this.resumeHasAnalysis && this.retryCount >= this.MAX_RETRY_TIMES) {
        uni.showToast({
          title: "超过最大重试次数，简历仍在解析中，请稍后重新进来此页面",
          icon: "none",
          duration: 1500,
        });
        this.endRequest();
      }
    },
    //刷新个人信息
    getPersonDetail() {
      {
        let param = {
          param: JSON.stringify({
            personId: this.personId,
          }),
          where: "",
          slaveInfo: 1,
        };
        getPersonDetail(param).then((res) => {
          let data = res.data || res;
          if (
            data.pic &&
            data.pic.indexOf("img.job1001.com/myUpload/pic.gif") >= 0
          ) {
            data.pic = this.$defalutAvatar;
          }
          getApp().globalData.userInfo = data;
        });
      }
    },
    // 获取在线简历信息
    async getResumeDataFn() {
      uni.showLoading({ title: "" });
      let param = {
        personId: this.personId,
        conditionArr: JSON.stringify({
          is_mp: 1,
        }),
      };
      const res = await getResumeData(param);
      uni.hideLoading();
      if (res.code == 200) {
        getApp().globalData.resumeInfo = res.data;
        const { personEdusArr, myTended } = res.data;
        if (personEdusArr && personEdusArr.length > 0) {
          this.majorParams.major = personEdusArr[0].zye || "";
          this.form.major = personEdusArr[0].zye || "";
        }
        if (myTended && myTended.length > 0) {
          this.wantJobParams.position = myTended[0].zwname;
          this.wantJobParams.intendedId = myTended[0].intended_id;
          this.form.position = myTended[0].zwname;
        }
      }
    },
    handleSelect(index) {
      switch (index) {
        case 0:
          this.showResumeType = true;
          break;
        case 1:
          this.showMajorList = true;
          break;
        case 2:
          this.showWantJob = true;
          break;
        default:
          break;
      }
    },
    handleSelectResumeType(item) {
      this.form.attName = item.name;
      this.resumeParams = { attName: item.name, attUrl: item.url };
      this.getResumeDataFn();
    },
    handleGetResumeParams(item) {
      const val = JSON.parse(item);
      console.log("val", val);
      this.resumeParams = val;
      this.form.attName = this.resumeParams.attName;
      // 1: 上传简历 2: 在线简历
      if (val.type == "1") {
        this.syncDealResumeAnalysisAndSaveFn();
      } else {
        this.getResumeDataFn();
      }
    },
    handleSelectResume(item) {
      this.showResumeType = false;
    },
    handleGetMajorParams(val) {
      if (val) {
        this.majorParams = JSON.parse(val);
        this.form.major = this.majorParams.major;
      }
      this.showMajorList = false;
    },
    handleCloseMajorListPopup() {
      this.showMajorList = false;
    },
    handleGetWantJobParams(val) {
      if (val) {
        this.wantJobParams = JSON.parse(val);
        this.form.position = this.wantJobParams.position;
      }
      this.showWantJob = false;
    },
    handleCloseWantJobPopup() {
      this.showWantJob = false;
    },
    handleCloseResumeType() {
      this.showResumeType = false;
    },
    handleCloseResumeListPopup() {
      this.showResumeType = true;
    },
    handleSubmit() {
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          const diagnosisParams = {
            majorParams: this.majorParams,
            wantJobParams: this.wantJobParams,
            resumeParams: this.resumeParams,
          };
          const res = await this.capacityDiagnoseFn(diagnosisParams);
          if (res.code == 200) {
            uni.setStorageSync(
              "diagnosisParams",
              JSON.stringify(diagnosisParams)
            );
            if (this.fromSxh == "sxh") {
              this.createQRFn();
            } else {
              this.addBuryingPointFn("50025", "", "", "", "");
              uni.navigateTo({
                url: `/pagesSub/newResume/resumeAssessment/index?fromSxh=${this.fromSxh}`,
              });
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
              duration: 1500,
            });
          }
        } else {
          console.log("验证失败");
        }
      });
    },
    async capacityDiagnoseFn(val) {
      const openId = uni.getStorageSync("openId");
      const info = {
        position: val.wantJobParams.position,
        intendedId: val.wantJobParams.intendedId,
        major: val.majorParams.major,
        attName: val.resumeParams.attName,
        type: val.resumeParams.type,
        attUrl: val.resumeParams.attUrl || "",
        updateTime: val.resumeParams.updateTime || "",
      };
      const params = {
        openId: openId,
        personId: this.personId,
        info: JSON.stringify(info),
      };
      const res = await capacityDiagnose(params);
      return res;
    },
    handleDownload(item) {
      uni.showLoading({
        title: "正在打开简历",
      });
      uni.downloadFile({
        url: item.attUrl,
        success: (res) => {
          if (+res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: function (saveRes) {
                setTimeout(() => {
                  uni.hideLoading();
                  uni.openDocument({
                    filePath: saveRes.savedFilePath,
                  });
                }, 1500);
              },
            });
          }
        },
      });
    },
    //普通的埋点+事件停留埋点
    async addBuryingPointFn(
      etId,
      statType,
      jumpPersonId,
      jumpSource,
      sourceType
    ) {
      const params = {
        etId: etId,
        id: this.buryingPointId ? this.buryingPointId : "", //后台要求不能传空，未登录也要统计
        personId: uni.getStorageSync("person-id").slice(2) || "0",
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync("cardType") || this.cardType,
        consultantId: uni.getStorageSync("sellId")
          ? uni.getStorageSync("sellId")
          : "",
        originType: 20,
        statType: statType ? statType : "10",
        jumpPersonId: jumpPersonId,
        jumpSource: jumpSource,
        sourceType: sourceType,
      };
      const res = await addBuryingPoint(params);
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base: $img-base;

.ai-resume-diagnose-new {
  min-height: 100vh;
  background-color: #fdfeff;
  padding: 0 32rpx;
  color: $uni-text-color-333;
  position: relative;
  padding-bottom: calc(42rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(42rpx + env(safe-area-inset-bottom));
  background-image: url($img-base + "resume/newResumeBG.png");
  background-size: 100% auto;
  background-repeat: no-repeat;

  .title-box {
    margin: 58rpx 0 138rpx 0;
    .title {
      font-size: 48rpx;
      font-weight: 600;
      color: #222;
    }
    .title-desc {
      font-size: 28rpx;
      color: #333;
      margin-top: 18rpx;
    }
  }
  .form {
    ::v-deep .u-form {
      margin-left: 15rpx;
    }
    ::v-deep .u-form-item {
      padding: 44rpx 0;
    }
    ::v-deep .u-form-item--left__content__label {
      font-size: 36rpx;
      color: #222222;
    }
    .file {
      display: flex;
      align-items: center;
      background: #f3f3f4;
      padding: 24rpx 0 24rpx 20rpx;
      border-radius: 8rpx;
      margin: 24rpx 0 40rpx 0;
      .file-icon {
        width: 68rpx;
        height: 68rpx;
        flex-shrink: 0;
      }
      .file-name {
        flex: 1;
        display: flex;
        flex-direction: column;
        margin-left: 24rpx;
        .att_name {
          width: 520rpx;
          font-size: 32rpx;
          color: #222222;
          line-height: 40rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .date {
          font-size: 24rpx;
          line-height: 32rpx;
          color: #bfa0a0;
          margin-top: 8rpx;
        }
      }
    }
  }
  .footer {
    width: 100%;
    height: 80rpx;
    position: fixed;
    bottom: calc(36rpx + constant(safe-area-inset-bottom));
    bottom: calc(36rpx + env(safe-area-inset-bottom));
    .btn {
      width: calc(100% - 64rpx);
      border-radius: 12rpx;
      background: #f75a3e;
      color: #fff;
      text-align: center;
    }
  }
}
</style>
